/**
 * @fileOverview
 * @name d-pipe.js
 * @author diqye
 * @license 喜欢fp的可以加群426566496
 */
!function(exports,R){
    var conf = [
        ["d-click", onclickfn],
        ["d-keyup", onkeyupfn]
    ];

    function scopeel(els) {
        return R.head(els);
    }

    function cel(els) {
        return R.last(els);
    }

    function onclickfn(els, stree, scope) {
        cel(els).on("click", function() {
            return deval(els, stree, scope);
        });
        return cel(els);
    }

    function onkeyupfn(els, stree, scope) {
        cel(els).on("keyup", function() {
            return deval(els, stree, scope);
        });
        return cel(els);
    }
    var find = R.curry(function(selector, el) {
        return el.find(selector);
    });

    function getAttr(attr, el) {
        return el.attr(attr);
    }

    function deval(els, stree, scope) {
        function getfn(a) {
            var r = scope[a.fn] || R[a.fn];
            if (r == null) throw a.fn + "函数找不到";
            return r;
        }
        var thisQueryfn = R.ifElse(R.pipe(R.prop("I"),
                                          R.equals("other")),
                                   R.ifElse(R.pipe(R.prop("token"),
                                                   R.equals("this")),
                                            R.always(cel(els)),
                                            R.pipe(R.prop("token"),
                                                   find(R.__, scopeel(els)))),
                                   R.identity);
        return R.reduce(function(arg, dfn) {
            if (arg === undefined) return R.apply(getfn(dfn), R.map(thisQueryfn, dfn.args));
            return R.apply(getfn(dfn), R.concat(R.map(thisQueryfn, dfn.args), [arg]));
        }, undefined, stree);
    }

    function dpipe(el, scope) {
        return R.map(function(cf) {
            find("[" + R.head(cf) + "]", el).each(function() {
                var iel = $(this);
                var attrstr = getAttr(R.head(cf), iel);
                if (attrstr == null || attrstr == "") return;
                var stree = dlang.parserWithPipe(attrstr);
                return R.last(cf)([el, iel], stree, scope);
            });
        }, conf);
    }
    exports.dpipe={
        dpipe:dpipe
    };
}(this,R);
